package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.*;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.encode.Base64Utils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyMeiXinQianBao;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeMeiXinQianBao;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformMultiPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMaskConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 美信钱包
 *
 * 全流程 - 文档：https://tcn3cl8mfuw3.feishu.cn/docx/F39pdJ1PFoWP08xredcc7X56nze
 *          密码：meixin2025
 *
 * @author gwc
 * @create 2025-07-28 下午2:42
 */

@ApiPlan(productId = "377", type = ApiPlanConvertType.PLAT_PHONE_MASK)
public class ApiPlatMeiXinQianBaoPhoneMask implements ApiPlatformPhoneMaskConvertHandler {

    /**
     *  渠道编号
     */
    public static final String ORG_ID = "axfq-2";
    public static final String KEY = "LVV8jVK38pesHAz1";
    public static final String IV = "fDDS6NKSGVdeBe4n";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        //  创建对应撞库实体类
        ApiPlatDataExchangeMeiXinQianBao meiXinQianBaoData = new ApiPlatDataExchangeMeiXinQianBao();
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiDataExchangeParameter);
        //  8位掩码
        meiXinQianBaoData.setPhoneMask(apiDataExchangeParameter.getPhoneMask());
        //  IP地址（必填）
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getIp())) {
            meiXinQianBaoData.setIp(apiDataExchangeParameter.getIp());
        } else {
            meiXinQianBaoData.setIp("127.0.0.1");
        }
        //  城市；如：北京市（必填）
        meiXinQianBaoData.setCity(apiDataExchangeParameter.getCity());
        //  年龄（必填）
        meiXinQianBaoData.setAge(apiFieldConverter.getAgeInt());
        //  性别；1：男 2：女（必填）
        Integer sex = ChooseEq.create(apiDataExchangeParameter.getSex())
                .when("0", 1)
                .when("1", 2)
                .end(1);
        meiXinQianBaoData.setGender(sex);
        //  贷款额度；1：3万；2：5万；3：10万；4:20万（必填）
        Integer money = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanAmount(), "1", 1)
                .when(apiDataExchangeParameter.getLoanAmount(), "2", 2)
                .when(apiDataExchangeParameter.getLoanAmount(), "3", 3)
                .when(apiDataExchangeParameter.getLoanAmount(), "4", 4)
                .end(1);
        meiXinQianBaoData.setLoanAmount(money);
        //  贷款时间；1：6个月；2：12个月；3：24个月；4：36个月（必填）
        Integer loanTerm = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanTerm(), "1", 1)
                .when(apiDataExchangeParameter.getLoanTerm(), "2", 1)
                .when(apiDataExchangeParameter.getLoanTerm(), "3", 2)
                .when(apiDataExchangeParameter.getLoanTerm(), "4", 3)
                .when(apiDataExchangeParameter.getLoanTerm(), "5", 4)
                .when(apiDataExchangeParameter.getLoanTerm(), "6", 4)
                .end(1);
        meiXinQianBaoData.setLoanTime(loanTerm);
        //  职业；1：上班族； 2：自由职业；3：私营企业主；4：公务员/国企（必填）
        Integer job = ChooseEq.create()
                .when(apiDataExchangeParameter.getCareer(), "1", 1)
                .when(apiDataExchangeParameter.getCareer(), "2", 2)
                .when(apiDataExchangeParameter.getCareer(), "3", 3)
                .when(apiDataExchangeParameter.getCareer(), "4", 4)
                .when(apiDataExchangeParameter.getCareer(), "5", 3)
                .end(1);
        meiXinQianBaoData.setProfession(job);
        //  芝麻分；1：600以下；2：600-650分；3：650-700分；4：700以上；5：无（必填）
        String zhima = ChooseEq.create()
                .when(apiDataExchangeParameter.getSesameCredit(), "1", "1")
                .when(apiDataExchangeParameter.getSesameCredit(), "2", "2")
                .when(apiDataExchangeParameter.getSesameCredit(), "3", "3")
                .when(apiDataExchangeParameter.getSesameCredit(), "4", "4")
                .end("5");
        meiXinQianBaoData.setZhima(zhima);
        //  公积金；1：6个月以下；2：6-12个月；3：12个月以上；4：无保单（必填）
        Integer gongjijin = ChooseEq.create()
                .when(apiDataExchangeParameter.getProvidentFund(), "1", 4)
                .when(apiDataExchangeParameter.getProvidentFund(), "2", 1)
                .when(apiDataExchangeParameter.getProvidentFund(), "3", 2)
                .when(apiDataExchangeParameter.getProvidentFund(), "4", 1)
                .end(4);
        meiXinQianBaoData.setProvidentFund(gongjijin);
        //  社保；1：6个月以下；2：6-12个月；3：12个月以上；4：无保单（必填）
        Integer shebao = ChooseEq.create()
                .when(apiDataExchangeParameter.getSocialSecurity(), "1", 4)
                .when(apiDataExchangeParameter.getSocialSecurity(), "2", 1)
                .when(apiDataExchangeParameter.getSocialSecurity(), "3", 2)
                .when(apiDataExchangeParameter.getSocialSecurity(), "4", 1)
                .end(4);
        meiXinQianBaoData.setSocialSecurity(shebao);
        //  名下房产；1：有房产；2：无房产（必填）
        Integer house = ChooseEq.create()
                .when(apiDataExchangeParameter.getRealEstateInfo(), "1", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "2", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "3", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "4", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "5", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "6", 1)
                .end(2);
        meiXinQianBaoData.setHouse(house);
        //  名下车产；1：有车产；2：无车产（必填）
        Integer car = ChooseEq.create()
                .when(apiDataExchangeParameter.getCarInfo(), "1", 2)
                .when(apiDataExchangeParameter.getCarInfo(), "2", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "3", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "4", 1)
                .end(2);
        meiXinQianBaoData.setVehicle(car);
        //  逾期记录；1：信用良好；2：当前逾期中（必填）
        Integer overdue = ChooseEq.create()
                .when(apiDataExchangeParameter.getOverdue(), "1", 1)
                .when(apiDataExchangeParameter.getOverdue(), "2", 2)
                .when(apiDataExchangeParameter.getOverdue(), "3", 1)
                .end(2);
        meiXinQianBaoData.setOverdue(overdue);
        //  保单；0：6个月以下；1：6-12个月；2：12个月以上；3：无保单（必填）
        Integer baodanIs = ChooseEq.create()
                .when(apiDataExchangeParameter.getInsurancePolicy(), "1", 3)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "2", 1)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "3", 2)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "4", 0)
                .end(3);
        meiXinQianBaoData.setCommericalInsurance(baodanIs);
        //  加密data
        String encode = Base64Utils.encodeToStr(JsonUtils.toJson(meiXinQianBaoData));
        AES aes = AES.createCbc(KEY.getBytes(), IV.getBytes());
        String data = aes.encryptToBase64Str(encode);
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("orgId", ORG_ID);
            newMap.put("data", data);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformMultiPhoneMaskDataExchange respDataExchange(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        // 获取响应数据
        JSONObject resData = jsonObject.getJSONObject("data");
        if (ValidParam.isEmpty(resData)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }

        RespPlatformMultiPhoneMaskDataExchange respPlatformMultiPhoneMaskDataExchange = RespPlatformMultiPhoneMaskDataExchange.ofSuc();
        List<RespPlatformPhoneMaskDataExchange> listRespPlatformPhoneMaskDataExchange = CollUtils.newArrayList();

        //  获取携带参数
        String orderId = resData.getString("orderId");
        String productName = resData.getString("productName");
        BigDecimal price = resData.getBigDecimal("price");
        String companyName = resData.getString("productName");
        //  用户协议
        List<ApiProtocol> protocolList = new ArrayList<>();
        //  获取协议
        JSONArray listProtocolResult = resData.getJSONArray("contractList");
        IteratorUtils.array(listProtocolResult, (item, index) -> {
            JSONObject protocolObject = listProtocolResult.getJSONObject(index);
            ApiProtocol protocol = new ApiProtocol();
            protocol.setProtocolName(protocolObject.getString("contractName"));
            protocol.setProtocolUrl(protocolObject.getString("contractUrl"));
            protocolList.add(protocol);
        });
        //  获取手机号掩码
        List<String> listPhoneMd5 = new ArrayList<>();
        JSONArray jsonArray = resData.getJSONArray("md5MobileList");
        IteratorUtils.array(jsonArray, (item, index) -> {
            String phoneMd5  = jsonArray.getString(index);
            listPhoneMd5.add(phoneMd5);
        });

        RespPlatformPhoneMaskDataExchange result = RespPlatformPhoneMaskDataExchange.of();
        result.setApplyId(orderId);
        result.setProductName(productName);
        result.setProtocolList(protocolList);
        result.setListPhoneMd5(listPhoneMd5);
        result.setDisplayName(companyName);
        result.setPrice(price);
        listRespPlatformPhoneMaskDataExchange.add(result);

        respPlatformMultiPhoneMaskDataExchange.setListPhoneMask(listRespPlatformPhoneMaskDataExchange);
        return respPlatformMultiPhoneMaskDataExchange;
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        //  创建对应进件实体类
        ApiPlatApplyMeiXinQianBao meiXinQianBaoData = new ApiPlatApplyMeiXinQianBao();
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        //  姓名（必填）
        meiXinQianBaoData.setName(apiApplyParameter.getUserName());
        //  手机号（必填）
        meiXinQianBaoData.setPhone(apiApplyParameter.getPhone());
        //  IP地址（必填）
        if (ValidParam.isNotEmpty(apiApplyParameter.getIp())) {
            meiXinQianBaoData.setIp(apiApplyParameter.getIp());
        } else {
            meiXinQianBaoData.setIp("127.0.0.1");
        }
        //  城市；如：北京市（必填）
        meiXinQianBaoData.setCity(apiApplyParameter.getCity());
        //  年龄（必填）
        meiXinQianBaoData.setAge(apiFieldConverter.getAgeInt());
        //  性别；1：男 2：女（必填）
        Integer sex = ChooseEq.create(apiApplyParameter.getSex())
                .when("0", 1)
                .when("1", 2)
                .end(1);
        meiXinQianBaoData.setGender(sex);
        //  贷款额度；1：3万；2：5万；3：10万；4:20万（必填）
        Integer money = ChooseEq.create()
                .when(apiApplyParameter.getLoanAmount(), "1", 1)
                .when(apiApplyParameter.getLoanAmount(), "2", 2)
                .when(apiApplyParameter.getLoanAmount(), "3", 3)
                .when(apiApplyParameter.getLoanAmount(), "4", 4)
                .end(1);
        meiXinQianBaoData.setLoanAmount(money);
        //  贷款时间；1：6个月；2：12个月；3：24个月；4：36个月（必填）
        Integer loanTerm = ChooseEq.create()
                .when(apiApplyParameter.getLoanTerm(), "1", 1)
                .when(apiApplyParameter.getLoanTerm(), "2", 1)
                .when(apiApplyParameter.getLoanTerm(), "3", 2)
                .when(apiApplyParameter.getLoanTerm(), "4", 3)
                .when(apiApplyParameter.getLoanTerm(), "5", 4)
                .when(apiApplyParameter.getLoanTerm(), "6", 4)
                .end(1);
        meiXinQianBaoData.setLoanTime(loanTerm);
        //  职业；1：上班族；2：自由职业；3：私营企业主；4：公务员/国企（必填）
        Integer job = ChooseEq.create()
                .when(apiApplyParameter.getCareer(), "1", 1)
                .when(apiApplyParameter.getCareer(), "2", 2)
                .when(apiApplyParameter.getCareer(), "3", 3)
                .when(apiApplyParameter.getCareer(), "4", 4)
                .when(apiApplyParameter.getCareer(), "5", 3)
                .end(1);
        meiXinQianBaoData.setProfession(job);
        //  芝麻分；1：600以下；2：600-650分；3：650-700分；4：700以上；5：无（必填）
        String zhima = ChooseEq.create()
                .when(apiApplyParameter.getSesameCredit(), "1", "1")
                .when(apiApplyParameter.getSesameCredit(), "2", "2")
                .when(apiApplyParameter.getSesameCredit(), "3", "3")
                .when(apiApplyParameter.getSesameCredit(), "4", "4")
                .end("5");
        meiXinQianBaoData.setZhima(zhima);
        //  公积金；1：6个月以下；2：6-12个月；3：12个月以上；4：无保单（必填）
        Integer gongjijin = ChooseEq.create()
                .when(apiApplyParameter.getProvidentFund(), "1", 4)
                .when(apiApplyParameter.getProvidentFund(), "2", 1)
                .when(apiApplyParameter.getProvidentFund(), "3", 2)
                .when(apiApplyParameter.getProvidentFund(), "4", 1)
                .end(4);
        meiXinQianBaoData.setProvidentFund(gongjijin);
        //  社保；1：6个月以下；2：6-12个月；3：12个月以上；4：无保单（必填）
        Integer shebao = ChooseEq.create()
                .when(apiApplyParameter.getSocialSecurity(), "1", 4)
                .when(apiApplyParameter.getSocialSecurity(), "2", 1)
                .when(apiApplyParameter.getSocialSecurity(), "3", 2)
                .when(apiApplyParameter.getSocialSecurity(), "4", 1)
                .end(4);
        meiXinQianBaoData.setSocialSecurity(shebao);
        //  名下房产；1：有房产；2：无房产（必填）
        Integer house = ChooseEq.create()
                .when(apiApplyParameter.getRealEstateInfo(), "1", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "2", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "3", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "4", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "5", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "6", 1)
                .end(2);
        meiXinQianBaoData.setHouse(house);
        //  名下车产；1：有车产；2：无车产（必填）
        Integer car = ChooseEq.create()
                .when(apiApplyParameter.getCarInfo(), "1", 2)
                .when(apiApplyParameter.getCarInfo(), "2", 1)
                .when(apiApplyParameter.getCarInfo(), "3", 1)
                .when(apiApplyParameter.getCarInfo(), "4", 1)
                .end(2);
        meiXinQianBaoData.setVehicle(car);
        //  逾期记录；1：信用良好；2：当前逾期中（必填）
        Integer overdue = ChooseEq.create()
                .when(apiApplyParameter.getOverdue(), "1", 1)
                .when(apiApplyParameter.getOverdue(), "2", 2)
                .when(apiApplyParameter.getOverdue(), "3", 1)
                .end(2);
        meiXinQianBaoData.setOverdue(overdue);
        //  保单；0：6个月以下；1：6-12个月；2：12个月以上；3：无保单（必填）
        Integer baodanIs = ChooseEq.create()
                .when(apiApplyParameter.getInsurancePolicy(), "1", 3)
                .when(apiApplyParameter.getInsurancePolicy(), "2", 1)
                .when(apiApplyParameter.getInsurancePolicy(), "3", 2)
                .when(apiApplyParameter.getInsurancePolicy(), "4", 0)
                .end(3);
        meiXinQianBaoData.setCommericalInsurance(baodanIs);
        //  掩码撞库必传（可选）
        meiXinQianBaoData.setOrderId(apiApplyParameter.getApplyId());
        //  加密data
        String encode = Base64Utils.encodeToStr(JsonUtils.toJson(meiXinQianBaoData));
        AES aes = AES.createCbc(KEY.getBytes(), IV.getBytes());
        String data = aes.encryptToBase64Str(encode);
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("orgId", ORG_ID);
            newMap.put("data", data);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMaskApply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        return RespPlatformPhoneMaskApply.ofSuc();
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }
}
